//
//  TJChatController.m
//  XWC
//
//  Created by Hello on 2022/10/24.
//

#import "HJChatController.h"
#import "HJInputController.h"
#import "HJIM.h"
#import "HJChatMessageLayoutHeader.h"
#import "TUIDefine.h"
#import "HJSingleChatController.h"
#import "HJGroupChatController.h"
#import "HJChatMessageVoiceCell.h"
#import "HJChatMessageImageCell.h"
#import "HJChatMessageVideoCell.h"
#import "HJChatMessageModel.h"
#import "HJAlertController.h"
#import "HJSelectFile.h"
#import "HJPhotoBrowser.h"
 
@interface HJChatController ()<HJInputControllerDelegate, TJMessageControllerDelegate, UINavigationControllerDelegate,UIImagePickerControllerDelegate>

 
@property (nonatomic, weak) HJInputController *inputController;

@property (nonatomic, assign) BOOL responseKeyboard;
@property (nonatomic, assign) BOOL firstAppear;
@property (nonatomic, assign) BOOL hasClearReadFire;
@property (nonatomic, strong) HJSelectFile *selectFile;


@end

@implementation HJChatController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    if (isEmptyString(self.sessionModel.sessionId) || [self.sessionModel.sessionId isEqualToString:HJUserInfo.userId options:NSCaseInsensitiveSearch]) {
        return;
    }
    
    self.navigationBar.title = self.sessionModel.sessionName;
    
    IQKeyboardManager.sharedManager.enable = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self addMessageController];
    [self addInputController];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleReceiveNewMessageNotification:) name:receiveNewMessageNotification object:nil];
}

- (void)handleReceiveNewMessageNotification:(NSNotification *)not {
    dispatch_async_main_queue(^{
        HJChatMessageModel *messageModel = not.object;
        if (![self.navigationController.viewControllers containsObject:self]) return;
        
        //要去查找么
        if ([messageModel.sessionId isEqualToString:self.sessionModel.sessionId]) {
            HJChatMessageLayout *messageLayout = [HJChatMessageLayout messagelayoutWithMessageModel:messageModel];
            [messageLayout calculateLayoutWithModel:messageModel lastMessageTime:self.messageController.messageLayouts.lastObject.messageModel.timestamp.integerValue];
            
            [self.messageController addNewMessage:messageLayout];
            [[NSNotificationCenter defaultCenter] postNotificationName:clearUnReadMessageNotification object:messageModel.sessionId];
            
            [HJIM.shareIM.userManager readMessageWithType:messageModel.chatType sessionId:messageModel.sessionId msgIds:@[messageModel.serverMsgId] begin:nil completion:nil];
        }
    });
}

+ (instancetype)chatControllerWithSessionModel:(HJChatSessionModel *)sessionModel {
    HJChatController *chatController = nil;
    if (sessionModel.chatType == HJChatTypeGroup) {
        chatController = [[HJGroupChatController alloc] init];
    } else if (sessionModel.chatType == HJChatTypeSingle) {
        chatController = [[HJSingleChatController alloc] init];
    }
    chatController.sessionModel = sessionModel;
    return chatController;
}

- (void)addMessageController {
    
    HJMessageController *messageController = [[HJMessageController alloc] init];
    messageController.sessionModel = self.sessionModel;
    messageController.delegate = self;
    messageController.view.frame = CGRectMake(0, KNavBarHight,
                                              self.view.frame.size.width,
                                              self.view.frame.size.height - TTextView_Height - TabbarSafeBottomMargin - KNavBarHight);
    [self addChildViewController:messageController];
    [self.view addSubview:messageController.view];
    [messageController didMoveToParentViewController:self];
    _messageController = messageController;
}

- (void)addInputController {
    HJInputController *inputController = [[HJInputController alloc] init];
    inputController.view.frame = CGRectMake(0, self.view.frame.size.height - (TTextView_Height + TabbarSafeBottomMargin),
                                            self.view.frame.size.width,
                                            TTextView_Height + TabbarSafeBottomMargin);
    inputController.delegate = self;
    [self addChildViewController:inputController];
    [self.view addSubview:inputController.view];
    _inputController = inputController;

}

- (void)didTapInMessageController:(HJMessageController *)controller {
    [self.inputController reset];
}

- (void)messageControllerNeedResetInput:(HJMessageController *)controller {
    [self.inputController reset];
}

- (void)messageController:(HJMessageController *)controller onSelectMessageAvatar:(HJChatMessageCell *)cell {

}

- (void)messageController:(HJMessageController *)controller onLongSelectMessageAvatar:(HJChatMessageCell *)cell {
    
    
}

- (void)messageController:(HJMessageController *)controller didClickRetryButton:(HJChatMessageCell *)cell {
    
    [HJAlertController alertInController:self title:@"" message:@"您的信息尚未发送，点击“再试一次”重新发" left:^(HJAlertAction * _Nonnull action) {
        action.title = @"取消";
        action.titleColor = UIColor.tj_1A1A1AColor;
    } right:^(HJAlertAction * _Nonnull action) {
        action.title = @"再试一次";
        action.titleColor = UIColor.tj_blueColor;
        [action setHandler:^{
            [HJIM.shareIM.chatManager sendMessageWithModel:cell.messageLayout.messageModel begin:^(HJChatMessageModel * _Nonnull model) {
                [self.messageController updateMessage:cell.messageLayout];
            } completion:^(id  _Nullable response, NSError * _Nullable error) {
            }];
        }];
    }];
    
}

- (void)messageController:(HJMessageController *)controller onSelectMessageContent:(HJChatMessageCell *)cell {
    
    HJChatMessageLayout *messageLayout = cell.messageLayout;
    
    if (messageLayout.messageModel.messageType == HJMessageTypeVoice) {
        for (HJChatMessageLayout *cellLayout in self.messageController.messageLayouts) {
            if (cellLayout.messageModel.messageType != HJMessageTypeVoice) {
                continue;
            }
            HJChatMessageVoiceLayout *voiceLayout = (HJChatMessageVoiceLayout *)cellLayout;
            [voiceLayout stopVoiceMessage];
        }
        
        HJChatMessageVoiceLayout *voiceLayout = (HJChatMessageVoiceLayout *)messageLayout;
        [voiceLayout playVoiceMessage];
        cell.messageLayout.messageModel.voiceRead = @"1";
        ((HJChatMessageVoiceCell *)cell).voiceReadPointView.hidden = YES;
        [cell.messageLayout.messageModel bg_saveOrUpdate];
        return;
    }
    
    [self.inputController reset];
    if (messageLayout.messageModel.messageType == HJMessageTypeImage || messageLayout.messageModel.messageType == HJMessageTypeVideo) {
        
        NSMutableArray *mediaDatas = [NSMutableArray array];
        NSMutableArray *Marr = [NSMutableArray array];
        [self.messageController.messageLayouts enumerateObjectsUsingBlock:^(HJChatMessageLayout *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            if (obj.messageModel.messageType == HJMessageTypeImage || obj.messageModel.messageType == HJMessageTypeVideo) {
                [mediaDatas addObject:obj];
                
                HJChatMessageCell *souceCell = nil;
                for (HJChatMessageCell *visibleCell in self.messageController.tableView.visibleCells) {
                    if (visibleCell.messageLayout == obj || visibleCell.messageLayout.messageModel.msgId == obj.messageModel.msgId) {
                        souceCell = visibleCell;
                        break;
                    }
                }
                
                HJPhotoItem *item = [HJPhotoItem itemWithMessageModel:obj.messageModel];
                item.sourceView = souceCell.containerView;
                [Marr addObject:item];
            }
        }];
        
        NSInteger index = [mediaDatas indexOfObject:messageLayout];
        HJPhotoBrowser *browser = [HJPhotoBrowser browserWithPhotoItems:Marr selectedIndex:index];
        [browser showFromViewController:self];
        return;
    }
}

- (void)inputController:(HJInputController *)inputController didSelectMoreCell:(HJInputMoreCell *)cell {
    if ([cell.data.key isEqualToString:@"camera"]) {
        [self.selectFile openCameraInController:self complete:^(NSString * _Nonnull localPath, NSString * _Nonnull classFile, UIImage * _Nonnull image) {
            if ([classFile isEqualToString:@"video"]) {
                [self sendVideoMessageByLocalPath:localPath photo:image];
                return;
            }
            [self sendImageMessageByLocalPath:localPath];
        }];
        return;
    }
    
    if ([cell.data.key isEqualToString:@"album"]) {
        [self.selectFile selectPhotoInController:self complete:^(NSArray<UIImage *> * _Nonnull photos, NSArray * _Nonnull fileUrls) {
            [self sendMediaMessageByFileURLs:fileUrls photo:photos];
        }];
    }
 
}
 
- (HJSelectFile *)selectFile {
    if (!_selectFile) {
        _selectFile = [[HJSelectFile alloc] init];;
    }
    return _selectFile;
}

- (void)openImagePicker {
    [self.selectFile selectPhotoInController:self complete:^(NSArray<UIImage *> * _Nonnull photos, NSArray * _Nonnull assets) {
            
    }];
}
 


//
//- (void)chooseFromPhotoAlbum {
//    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
//    imagePickerController.delegate = self;
//
//    imagePickerController.allowsEditing = NO;
//    imagePickerController.modalPresentationStyle = UIModalPresentationFullScreen;
//    imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//    [self presentViewController:imagePickerController animated:YES completion:nil];
//}
//
- (void)chooseFromCamera {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.modalPresentationStyle = UIModalPresentationFullScreen;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:imagePickerController animated:YES completion:nil];
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    UIImage *image = (UIImage *)info[UIImagePickerControllerEditedImage];
    [picker dismissViewControllerAnimated:YES completion:^{
//        [self uploadImageWithImage:image];
        
    }];
}
 
- (void)inputController:(HJInputController *)inputController didChangeHeight:(CGFloat)height {
    
    if (!self.responseKeyboard) {
        return;
    }
    
    UIViewAnimationOptions animationOptions = 7 << 16;
    [UIView animateWithDuration:0.25 delay:0 options:animationOptions animations:^{
        CGRect msgFrame = self.messageController.view.frame;
        msgFrame.size.height = self.view.frame.size.height - KNavBarHight - height;
        self.messageController.view.frame = msgFrame;
        
        CGRect inputFrame = self.inputController.view.frame;
        inputFrame.origin.y = msgFrame.origin.y + msgFrame.size.height;
        inputFrame.size.height = height;
        self.inputController.view.frame = inputFrame;
        
        [self.messageController scrollToBottom:NO];
        
    } completion:nil];
    
}

- (void)inputController:(HJInputController *)inputController didSendTextMessage:(NSString *)text {
    [self sendTextMessageByText:text];
}

- (void)inputController:(HJInputController *)inputController didSendVoiceMessage:(NSString *)localPath {
    [self sendVoiceMessageByLocalPath:localPath];
}

- (void)inputControllerDidInputAt:(HJInputController *)inputController {
    
}

- (void)inputController:(HJInputController *)inputController didDeleteAt:(NSString *)atText {
    
}

- (void)sendMediaMessageByFileURLs:(NSArray <NSURL *> *)fileURLs photo:(NSArray <UIImage *> *)photo {}
- (void)sendTextMessageByText:(NSString *)text {}
- (void)sendMediaMessageByAsset:(PHAsset *)asset photo:(UIImage *)photo {}
- (void)sendMediaMessageByAssets:(NSArray <PHAsset *> *)asset photo:(NSArray <UIImage *> *)photo {}

- (void)sendVideoMessageByLocalPath:(NSString *)localPath photo:(UIImage *)photo {}
- (void)sendImageMessageByLocalPath:(NSString *)localPath {}
- (void)sendFileMessageByUrl:(NSURL *)URL{}
- (void)sendVoiceMessageByLocalPath:(NSString *)localPath {}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    IQKeyboardManager.sharedManager.enable = NO;
    
    self.responseKeyboard = YES;
    if (self.firstAppear) {
        self.firstAppear = NO;
    }
 
}
 
- (void)popViewController {
    [super popViewController];
    
    
}

- (void)clearReadFireMessage {
    dispatch_async_queue(^{
 
    });
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];

}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    if (![self.navigationController.viewControllers containsObject:self]) {
        [self clearReadFireMessage];
    }
    IQKeyboardManager.sharedManager.enable = YES;
    self.responseKeyboard = NO;
}

- (void)dealloc {
    NSLog(@"%s", __func__);
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}



@end
